<?php

define('DOC_ROOT', $_SERVER['DOCUMENT_ROOT']);

require_once DOC_ROOT . '/src/php/Utils.php';
require_once DOC_ROOT . '/src/php/Config.php';

$fn = export_db('jsdoc_pakinguo');

echo json_encode(array(
    'ret' => 0,
    'msg' => 'SUCCESS!',
    'data' => $fn
));

/*
 * 导出数据库数据
 */

function export_db($dbname) {
    $filename = "jsdoc_pakinguo_" . date('Y-m-d-h-i-s');
    $file = fopen(DOC_ROOT . "/sql_backup/$filename.sql", 'w');

    // 注释
    fwrite($file, "-- 生成日期: " . date('Y-m-d H:i:s') . "\n\n" . 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . "\n" . 'SET time_zone = "+00:00";' . "\n\n-- 数据库名: $dbname\n-- \nDROP DATABASE `$dbname`;\nCREATE DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;\nUSE `jsdoc_pakinguo`;\n\n-- --------------------------------------------------------\n\n");

    // 获取指定数据库的所有表
    $db_list = mysql_list_tables($dbname);

    // 建表
    while ($row = mysql_fetch_row($db_list)) {
        $tb_struct = mysql_fetch_assoc(mysql_query("show create table $row[0]"));
        // 写入结构
        fwrite($file, "-- 表结构: $row[0]\n-- \n" . str_replace('CREATE TABLE ', 'CREATE TABLE IF NOT EXISTS ', $tb_struct['Create Table']) . ";\n\n");
        // 写入数据
        fwrite($file, get_insert_sql($row[0]));
    }

    fclose($file);

    return $filename;
}

function get_insert_sql($table) {
    $rs = mysql_query("SELECT * FROM $table");
    if (mysql_num_rows($rs) < 1) {
        return "\n";
    }
    $sql = "INSERT INTO `$table` VALUES \n";
    $list = array();
    while ($row = mysql_fetch_row($rs)) {
        array_push($list, get_row_data($row));
    }
    $sql .= implode(",\n", $list) . ";\n";
    // 释放内存
    mysql_free_result($rs);
    return "-- 表数据: $row[0]\n-- \n$sql\n\n";
}

function get_row_data($row) {
    $values = array();
    foreach ($row as $value) {
        $values[] = "'" . mysql_real_escape_string($value) . "'";
    }
    return "(" . implode(', ', $values) . ")";
}